import React, { useState, useEffect,useRef } from "react";
import './index.scss'
import LlxTable from 'components/LlxTable'
import LlxForm from 'components/LlxForm/index'
import { Form ,Button,notification,Select,Divider,Cascader,DatePicker,Tag,Modal, message} from 'antd';
import { connect } from 'react-redux'
import {setPageData,addHistoryRouter,setDictionaries,getUserRole,getCount} from 'redux/action'
import {getDictionaries} from 'utils/index'

import { Menu, Dropdown, Space , Tooltip,Image} from 'antd';
import { DownOutlined ,ExclamationCircleOutlined} from '@ant-design/icons'

import {getWordList,getMessage,saveNewWord,materialAllWord,wordStatusChanges,wordStatusChangeBatch,pushPool,getRoleById,wordStatusChange,setRemark} from 'api/index'
import classNames from "classnames";


import  AudioUpload  from 'components/Upload/audio'
import  MoreUpload  from 'components/Upload/morePicture' 
import TaskAllocation from "components/Operations/task";

import ChangeStatus from "components/Operations/status";

import AddLabel from "components/Operations/AddLabel";

import DelLabel from "components/Operations/DelLabel";
const { RangePicker } = DatePicker;
const { SHOW_CHILD } = Cascader;
const { confirm } = Modal;


const ExamineWord = (props) => {

  const {isModalVisible, setIsModalVisible,dictionaries,examineData} = props

  const [form] = Form.useForm()

  const manager = examineData.wordStatus==='Q'||examineData.wordStatus==='PQ'?dictionaries.QandPQ:dictionaries.UserSpecies
  
  const item = ['Q','PQ'].includes(examineData.wordStatus)?[
    {label: '备注内容',type:'textArea', name: 'remark' , span: 24 }
]:[
    {label: '负责人', name: 'manager' , span: 24 ,rules:[
      {
        required: true,
        message: '请选择负责人'
      },
    ],render:()=>{
      return  <Select
      allowClear
      optionFilterProp="dictValue"
      showSearch
      fieldNames={{value:'userName',label:'userName'}}
      placeholder={'请选择负责人'}
      options={manager}
    >
    </Select>
    }},
    {label: '备注内容',type:'textArea', name: 'remark' , span: 24 }
]
// 返回
     const  getNewStatus = (value) => {
      switch (value) {
        case 'N':
          return 'R'
        case 'PN':
          return 'PR'
        case 'R':
          return 'Q'
        case 'Q':
          return 'P'
        case 'PR':
          return 'PQ'
        case 'PQ':
          return 'P'
          default:
            return
      }
    }
  const handleOk = () => {
    form.validateFields().then(async()=>{
      await wordStatusChange({
        id: examineData.id,
        wordStatus:getNewStatus(examineData.wordStatus),
        qmanager: ['R', 'PR','N','PN'].includes(examineData.wordStatus) ? form.getFieldValue().manager : '',
        rmanager: ''
      })
      // 留言
      await setRemark({
        manager: form.getFieldValue().manager,
        dataId: examineData.id,
        type: 'WORD',
        remark: form.getFieldValue().remark,
        statusNow: examineData.wordStatus,
        statusNext:getNewStatus(examineData.wordStatus)
      })

      message.success('审核通过')
      props.getNewList()

      setIsModalVisible(false)

    })
  }

  const handleCancel = () => {
    setIsModalVisible(false)
  }

  return   <Modal destroyOnClose width={950} title="审核单词" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
  <LlxForm form={form} labelCol={5} formItem={item} />
</Modal>
}


// 新增弹框
const AddWord = (props) =>{
  const {isModalVisible, setIsModalVisible,dictionaries,userName} = props

  const [form] = Form.useForm();//新增单词


  const loading = useRef(false)

   // 新增表单
   const newWordItem = [
  {label: '单词名称',type:'input', name: 'wordName' , span: 12 ,rules:[
    {
      required: true,
      message: '请输入单词名称'
    },
  ]},
  {label: '英文释义',type:'input', name: 'englishExplain' , span: 12 },
  {label: '中文释义',type:'input', name: 'chineseExplain' , span: 12 },
  {label: '词性', name: 'pofId', span: 12 ,render:()=>{
    return  <Select
    allowClear
    optionFilterProp="dictValue"
    showSearch
    fieldNames={{value:'id',label:'dictValue'}}
    placeholder={'请选择词性'}
    options={dictionaries.PartOfSpeech}
  >
  </Select>
  }},
  {label: '级别', name: 'levelId', span: 12 ,render:()=>{
    return   <Select
    allowClear
    optionFilterProp="dictValue"
    showSearch
    fieldNames={{value:'id',label:'dictValue'}}
    placeholder={'请选择级别'}
    options={dictionaries.Level}
  >
  </Select>
  }},
  {label: '标签', name: 'label', span: 12 ,render:()=>{
    return  <Cascader  maxTagCount="responsive" showCheckedStrategy={SHOW_CHILD} fieldNames={{value:'id',label:'labelName'}} options={dictionaries.Label} multiple placeholder="请选择标签" />
  }},
  {label: '音频', name: 'audioUrl', span: 13 ,rules:[
    {
      required: true,
      message: '请上传音频'
    },
  ],render:()=>{
    return  <AudioUpload audio={form.getFieldValue().audioUrl} setAudio={(value)=>form.setFieldsValue({...form.getFieldValue(),audioUrl:value})}></AudioUpload>
  }},
  {label: '写实图片', name: 'picRealistic', span: 12 ,render:()=>{
    return  <MoreUpload pictureList={form.getFieldValue().picRealistic}  setPhoto={(value)=>form.setFieldsValue({...form.getFieldValue(),picRealistic:value})}></MoreUpload>
  }},
  {label: '卡通图片', name: 'picCartoon', span: 12 ,render:()=>{
    return  <MoreUpload pictureList={form.getFieldValue().picCartoon}  setPhoto={(value)=>form.setFieldsValue({...form.getFieldValue(),picCartoon:value})}></MoreUpload>
  }},
  {label: '例句',type:'input', name: 'exampleSentence' , span: 12 },
  {label: '例句翻译',type:'input', name: 'exampleTranslate' , span: 12 },
  {label: '例句音频', name: 'exampleAudioUrl' , span: 13,render:()=>{
    return  <AudioUpload audio={form.getFieldValue().exampleAudioUrl} setAudio={(value)=>form.setFieldsValue({...form.getFieldValue(),exampleAudioUrl:value})}></AudioUpload>
  }}
   ]
   
   const handleOk = () => {
    if(loading.current) return
    
    loading.current=true
    form.validateFields().then(async()=>{

      const picRealistic = form.getFieldValue().picRealistic?form.getFieldValue().picRealistic.map(i=>{
        return {pictureUrl:i.url||i.pictureUrl,pictureType:0}
      }):[]
      const picCartoon = form.getFieldValue().picCartoon?form.getFieldValue().picCartoon.map(i=>{
        return {pictureUrl:i.url||i.pictureUrl,pictureType:1}
      }):[]
      
      const wdWordPictureFlows = [...picRealistic,...picCartoon]

      const data = {
        audioUrl: form.getFieldValue().audioUrl,
        chineseExplain: form.getFieldValue().chineseExplain,
        englishExplain: form.getFieldValue().englishExplain,
        levelId: form.getFieldValue().levelId || -99,
        pofId: form.getFieldValue().pofId || -99,
        wdWordExampleFlows:[
         {
          exampleAudioUrl: form.getFieldValue().exampleAudioUrl,
          exampleSentence: form.getFieldValue().exampleSentence,
          exampleTranslate: form.getFieldValue().exampleTranslate
         }
        ],
        wdWordPictureFlows,
        wordName: form.getFieldValue().wordName,
        labels:form.getFieldValue().label?.map(i=>{
          return {id:i[1]}
          })
        }
        
       await saveNewWord(data)

       notification.success({
          message: '新增成功',
          description: '操作人：' + userName,
          duration:1.5
        });
      
      form.resetFields()
      setIsModalVisible(false);

      props.getNewList()
    }).catch(err=>{
      notification.warning({
        message: '检查必填项',
        duration:1.5
      });
    }).finally(()=>{
      loading.current=false
    })
   };

  const handleCancel = () => {
    form.resetFields()
    setIsModalVisible(false);
  };

  return   <Modal width={950} title="新增单词" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
        <LlxForm form={form} labelCol={5} formItem={newWordItem} />
   </Modal>
}

function WordLibrary(props) {
const {dictionaries} = props
// 数据
const [loading,setLoading] = useState(false) //加载
const [expand,setExpand] = useState(false) //表单伸缩
const [total,setTotal] = useState(0) //总数量
const [isModalVisible, setIsModalVisible] = useState(false)
const [isModalVisibleTask, setIsModalVisibleTask] = useState(false)
const [isModalVisibleAddLabel, setIsModalVisibleAddLabel] = useState(false)
const [isModalVisibleDelLabel, setIsModalVisibleDelLabel] = useState(false)
const [isModalVisibleStatus, setIsModalVisibleStatus] = useState(false)
const [isModalVisibleExamineWord, setIsModalVisibleExamineWord] = useState(false)
const [selectData, setSelectData] = useState([])
const [form] = Form.useForm();//搜索列表
const [examineData,setExamineData] = useState({})
//选择数据
const [selectedRowKeys,setselectedRowKeys] = useState([])
const rowSelection  = useRef({
  selectedRowKeys: selectedRowKeys,
  onChange: value => {
  setselectedRowKeys(value)
  rowSelection.current.selectedRowKeys = value
  }
})

// 表单数据
const formItem = !props.examineStatus?[
  {label: '名称',type:'input', name: 'wordName', span: 4 },
  {label: '词性', name: 'pofId' , span: 5 ,render: () => {
    return <Select
    allowClear
    optionFilterProp="dictValue"
    showSearch
    fieldNames={{value:'id',label:'dictValue'}}
    placeholder={'请选择词性'}
    options={dictionaries.PartOfSpeech}
  >
  </Select>
}},
  {label: '状态', name: 'wordStatus', span: 5 ,render: () => {
    return <Select
    allowClear
    optionFilterProp="dictValue"
    showSearch
    fieldNames={{value:'dictValue',label:'dictValue'}}
    placeholder={'请选择状态'}
    options={dictionaries.wordStatus}
  >
  </Select>
}},
  {label: '级别', name: 'levelId' , span: 5,render: () => {
    return <Select
    allowClear
    optionFilterProp="dictValue"
    showSearch
    fieldNames={{value:'id',label:'dictValue'}}
    placeholder={'请选择级别'}
    options={dictionaries.Level}
  >
  </Select>
} },
  {label: '空值', name: 'isNull' , span: 5,render: () => {
    return <Select
    allowClear
    optionFilterProp="dictValue"
    showSearch
    fieldNames={{value:'id',label:'dictValue'}}
    placeholder={'请选择空值'}
    options={dictionaries.WordInfoIsNull}
  >
  </Select>
} },
 
  {label: '创建人', name: 'createBy',  span: 4 ,render: () => {
    return <Select
    allowClear
    optionFilterProp="userName"
    showSearch
    fieldNames={{value:'userName',label:'userName'}}
    placeholder={'请选择创建人'}
    options={dictionaries.UserSpecies}
  >
  </Select>
}},
  {label: '负责人', name: 'manager',  span: 4 ,render: () => {
    return <Select
    allowClear
    optionFilterProp="userName"
    showSearch
    fieldNames={{value:'userName',label:'userName'}}
    placeholder={'请选择负责人'}
    options={dictionaries.UserSpecies}
  >
  </Select>
}},
  {label: '更新人', name: 'updateBy',  span: 4 ,render: () => {
    return <Select
    allowClear
    optionFilterProp="userName"
    showSearch
    fieldNames={{value:'userName',label:'userName'}}
    placeholder={'请选择更新人'}
    options={dictionaries.UserSpecies}
  >
  </Select>
}},
{label: '标签', name: 'label' , span: 5,render: () => {
  return <Cascader  maxTagCount="responsive" showCheckedStrategy={SHOW_CHILD} fieldNames={{value:'id',label:'labelName'}} options={dictionaries.Label} multiple placeholder="请选择标签" />
} },
  {label: '更新时间', name: 'updateTime', span: 7 ,render: () => {
    return  <RangePicker showTime onChange={getUpdateTime} style={{width:'100%'}}/>
}}
]:[
  {label: '名称',type:'input', name: 'wordName', span: 4 },
  {label: '词性', name: 'pofId' , span: 5 ,render: () => {
    return <Select
    allowClear
    optionFilterProp="dictValue"
    showSearch
    fieldNames={{value:'id',label:'dictValue'}}
    placeholder={'请选择词性'}
    options={dictionaries.PartOfSpeech}
  >
  </Select>
}},
  {label: '级别', name: 'levelId' , span: 5,render: () => {
    return <Select
    allowClear
    optionFilterProp="dictValue"
    showSearch
    fieldNames={{value:'id',label:'dictValue'}}
    placeholder={'请选择级别'}
    options={dictionaries.Level}
  >
  </Select>
} },
  {label: '空值', name: 'isNull' , span: 5,render: () => {
    return <Select
    allowClear
    optionFilterProp="dictValue"
    showSearch
    fieldNames={{value:'id',label:'dictValue'}}
    placeholder={'请选择空值'}
    options={dictionaries.WordInfoIsNull}
  >
  </Select>
} },
 
  {label: '创建人', name: 'createBy',  span: 5 ,render: () => {
    return <Select
    allowClear
    optionFilterProp="userName"
    showSearch
    fieldNames={{value:'userName',label:'userName'}}
    placeholder={'请选择创建人'}
    options={dictionaries.UserSpecies}
  >
  </Select>
}},
  {label: '更新人', name: 'updateBy',  span: 5 ,render: () => {
    return <Select
    allowClear
    optionFilterProp="userName"
    showSearch
    fieldNames={{value:'userName',label:'userName'}}
    placeholder={'请选择更新人'}
    options={dictionaries.UserSpecies}
  >
  </Select>
}},
{label: '标签', name: 'label' , span: 5,render: () => {
  return <Cascader  maxTagCount="responsive" showCheckedStrategy={SHOW_CHILD} fieldNames={{value:'id',label:'labelName'}} options={dictionaries.Label} multiple placeholder="请选择标签" />
} },
  {label: '更新时间', name: 'updateTime', span: 7 ,render: () => {
    return  <RangePicker showTime onChange={getUpdateTime} style={{width:'100%'}}/>
}}
]
//分页数据
const [pagination,setPagination] = useState({
  current:1,
  pageSize:10
})
//初始表格数据
const [dataSource,setDataSource] = useState([])
//表头配置信息
const columns = !props.examineStatus?[
      {title: '序号', fixed:'left', dataIndex: 'sort', key: 'sort', align: 'center',width:50},
      {title: '单词', fixed:'left',dataIndex: 'wordName', key: 'wordName', align: 'center',width:120,render: (text, record) => {
        return <div className="operate_link_group text-nowrap text-link" onClick={()=>goWordInfo(record.id)}>
          {text}
       </div>
     }},
      {title: '词性', dataIndex: 'pofName', key: 'pofName', align: 'center',width:60},
      {title: '状态', dataIndex: 'wordStatus', key: 'wordStatus', align: 'center',width:60},
      {title: '级别', dataIndex: 'levelName', key: 'levelName', align: 'center',width:60},
      {title: '中文释义', dataIndex: 'chineseExplain', key: 'chineseExplain', align: 'center',width:150, },
      {title: '标签', dataIndex: 'labels', key: 'labels',width:150, align: 'center', render: (text, record) => {
       return <div className="operate_link_group text-nowrap">
        {record.labels?.map((i,j)=>{
          return   <Tooltip key={i.id} placement="top" title={text.map(i=>i.labelName).join(' ')}>
           {
             j<3?<Tag key={i.id} color="green">{i.labelName}</Tag>:''
           }
            </Tooltip>
        })}
      </div>
     }},
     {title: '卡通', dataIndex: 'picture', key: 'picture',width:170, align: 'center', render: (text, record) => {
        return <div className="operate_link_group text-nowrap photo-list">
         {record.picture?record.picture.map((i,j)=>{
           return  j<3?<Image
           key={j}
           width={40}
           src={i.pictureUrl}
         />:''
         }):''}
       </div>
     }},
     {title: '写实', dataIndex: 'pictures', key: 'pictures',width:170, align: 'center', render: (text, record) => {
      return <div className="operate_link_group text-nowrap photo-list">
          {record.pictures?record.pictures.map((i,j)=>{
           return   j<3?<Image
           key={j}
           width={40}
           src={i.pictureUrl}
         />:''
         }):''}
       </div>
     }},
      {title: '创建人', dataIndex: 'createBy', key: 'createBy',width:100, align: 'center',render: (text, record) => {
        return <div className={classNames(props.userInfo.user.userName===text?'operate_link_group text-nowrap text-color-red':"operate_link_group text-nowrap")}>
          {text}
       </div>
     }},
      {title: '负责人', dataIndex: 'manager', key: 'manager',width:100, align: 'center', render: (text, record) => {
        return <div className={classNames((props.userInfo.user.userName===record.qmanager)||(props.userInfo.user.userName===record.rmanager)?'operate_link_group text-nowrap text-color-red':"operate_link_group text-nowrap")}>
        {record.qmanager||record.rmanager}
       </div>
     }},
      {title: '更新人', dataIndex: 'updateBy', key: 'updateBy',width:100, align: 'center',render: (text, record) => {
        return  <div className={classNames(props.userInfo.user.userName===text?'operate_link_group text-nowrap text-color-red':"operate_link_group text-nowrap")}>
        {text}
     </div>
     }},
     {title: '更新时间', dataIndex: 'updateTime', key: 'updateTime', align: 'center',width:180},
     {title: '操作',fixed:'right', dataIndex: 'active', key: 'active', align: 'center',width:100,render:(text,row)=>{
       return <div>
         <span className="text-link" onClick={()=>examineWord(row)}>审核</span>
       </div>
     }},
]:[
  {title: '序号', dataIndex: 'sort', key: 'sort', align: 'center',width:50},
  {title: '单词', dataIndex: 'wordName', key: 'wordName',width:120, align: 'center',render: (text, record) => {
    return <div className="operate_link_group text-nowrap text-link" onClick={()=>goWordInfo(record.id)}>
      {text}
   </div>
 }},
  {title: '词性', dataIndex: 'pofName', key: 'pofName', width:60,align: 'center'},
  {title: '级别', dataIndex: 'levelName', key: 'levelName', width:60,align: 'center'},
  {title: '中文释义', dataIndex: 'chineseExplain', key: 'chineseExplain', width:150,align: 'center'},
  {title: '标签', dataIndex: 'labels', key: 'labels',width:150, align: 'center', render: (text, record) => {
   return <div className="operate_link_group text-nowrap">
    {record.labels?.map((i,j)=>{
      return   <Tooltip key={i.id} placement="top" title={text.map(i=>i.labelName).join(' ')}>
       {
         j<3?<Tag key={i.id} color="green">{i.labelName}</Tag>:''
       }
        </Tooltip>
    })}
  </div>
}},
{title: '卡通', dataIndex: 'picture', key: 'picture',width:170, align: 'center', render: (text, record) => {
  return <div className="operate_link_group text-nowrap photo-list">
   {record.picture?record.picture.map((i,j)=>{
     return  j<3?<Image
           key={j}
           width={40}
           src={i.pictureUrl}
         />:''
   }):''}
 </div>
}},
{title: '写实', dataIndex: 'pictures', key: 'pictures',width:170, align: 'center', render: (text, record) => {
return <div className="operate_link_group text-nowrap photo-list">
    {record.pictures?record.pictures.map((i,j)=>{
     return  j<3?<Image
           key={j}
           width={40}
           src={i.pictureUrl}
         />:''
   }):''}
 </div>
}},
  {title: '创建人', dataIndex: 'createBy', key: 'createBy', width:100,align: 'center',render: (text, record) => {
    return <div className={classNames(props.userInfo.user.userName===text?'operate_link_group text-nowrap text-color-red':"operate_link_group text-nowrap")}>
      {text}
   </div>
 }},
  {title: '更新人', dataIndex: 'updateBy', key: 'updateBy', width:100, align: 'center',render: (text, record) => {
    return  <div className={classNames(props.userInfo.user.userName===text?'operate_link_group text-nowrap text-color-red':"operate_link_group text-nowrap")}>
    {text}
 </div>
 }},
  {title: '更新时间', dataIndex: 'updateTime', key: 'updateTime', align: 'center',width:180}
]


// 初始化
//1缓存页面数据 缓存表单数据
useEffect(()=>{
  form.setFieldsValue(props.tabList.filter(i=>i.url==='word/wordLibrary')[0]?.data?.form)
  setPagination(props.tabList.filter(i=>i.url==='word/wordLibrary')[0]?.data?.pagination||{
    current:1,
    pageSize:10
  })
  getDictionaries(props.setDictionaries)

  const getRole = async() => {
    const roleId = props.userInfo.roles.map(i=>i.id)
    const data4 = []
    for(let i = 0;i<roleId.length;i++){
      const res1 = await getRoleById(roleId[i])
      data4.push(...res1.result)
    } 
     props.getUserRoleFn(data4.map(i=>i.perms)) //按钮权限
  }
  getRole()


  const getTaskCount = async () => {

    const res  = await getMessage()
    props.getCount(res.result)
  }

  getTaskCount()
  },[]) // eslint-disable-line react-hooks/exhaustive-deps


// 切换发布草稿素材
useEffect(()=>{
  // 获取数据
  getNewList()
},[props.examineStatus]) // eslint-disable-line react-hooks/exhaustive-deps

// 方法
// 1.获取数据
const getNewList=(value)=>{


  // 清空选中状态
   setselectedRowKeys(()=>[])
   rowSelection.current.selectedRowKeys=[]

   setLoading(true)


    const initialData = async () => {

      const {
        createBy,
        endTime,
        label,
        levelId,
        manager,
        pofId,
        wordName,
        startTime,
        updateBy,
        wordStatus,
      } = form.getFieldValue()
      
      // 转化标签
      const labels = label?label.map(i=>{
        return {id:i[1]}
      }):[]
      // 请求的数据
      const params = {
        currPage:value&&value.pageSize?value.current:pagination.current,
        pageSize:value&&value.pageSize?value.pageSize:pagination.pageSize,
        createBy,
        endTime,
        labels,
        levelId,
        manager,
        pofId,
        wordName,
        startTime,
        updateBy,
        wordStatus,
        status: 1,
      }

      if(props.tabList.filter(i=>i.url==='word/wordLibrary')[0]?.data?.pagination&&(props.tabList.filter(i=>i.url==='word/wordLibrary')[0]?.data?.pagination.current!==1||props.tabList.filter(i=>i.url==='word/wordLibrary')[0]?.data?.pagination.pageSize!==10)&&pagination.current===1&&pagination.pageSize===10){
        params.currPage=props.tabList.filter(i=>i.url==='word/wordLibrary')[0]?.data?.pagination.current
        params.pageSize=props.tabList.filter(i=>i.url==='word/wordLibrary')[0]?.data?.pagination.pageSize
      }
      // 缓存数据
      const data = {
        pagination: value&&value.pageSize?value:pagination,
        form:form.getFieldValue()
      }
      
       props.setPageDataFn('word/wordLibrary',data) 

      // 空值判断
      if (form.getFieldValue().isNull) {
        if (form.getFieldValue().isNull === 1) {
          params.levelIdIsNull = true
        } else if (form.getFieldValue().isNull === 2) {
          params.pofIdIsNull = true
        } else {
          params.chineseExplainIsNull = true
        }
      }
      //  请求数据
      if(!props.examineStatus){
        const res = await getWordList(params)
        const data = res.result.records || []
        data.forEach((i,y)=>{
          i.sort =value&&value.pageSize?value.pageSize * (value.current - 1) + y + 1:pagination.pageSize * (pagination.current - 1) + y + 1
          i.picture = i.pictureFlows ? i.pictureFlows.filter(i => i.pictureType === '1') : [] //卡通
          i.pictures = i.pictureFlows ? i.pictureFlows.filter(i => i.pictureType === '0') : []//写实
        })
        
        setDataSource(data)
  
        setTotal(res.result.total)
      } else {
        const res = await materialAllWord(params)
        const data = res.result.records || []
        data.forEach((i,y)=>{
          i.sort =value&&value.pageSize?value.pageSize * (value.current - 1) + y + 1:pagination.pageSize * (pagination.current - 1) + y + 1
          i.picture = i.wdWordPictures ? i.wdWordPictures.filter(i => i.pictureType === '1') : [] //卡通
          i.pictures = i.wdWordPictures ? i.wdWordPictures.filter(i => i.pictureType === '0') : []//写实
        })
        
        setDataSource(data)
  
        setTotal(res.result.total)
      }
    

      setLoading(false)
    
    }
  
    initialData()
}
// 2.重置表单
const resetForm=()=>{
   form.resetFields()
   setPagination({
    current:1,
    pageSize:10
   })
   getNewList()
}
// 3.审核单词
const examineWord = (value) =>{
   
  if(value.wordStatus==='P') return message.error('该数据已发布')
  if(['N','PN'].includes(value.wordStatus)&&props.userInfo.user.userName!==value.createBy) return  message.error('你不是创建人')
  if(['Q','R','PQ','PR'].includes(value.wordStatus)&&(props.userInfo.user.userName!==value.qmanager||props.userInfo.user.userName!==value.rmanager)) return  message.error('你不是负责人')

  setExamineData(value)
  setIsModalVisibleExamineWord(true)
}
//  4.单词详情
const goWordInfo = (id) => {
props.history.push('/view/word/wordInfo?id=' + id)
props.addRouter({
  menuName:'单词详情',url:'word/wordInfo?id=' + id 
})
}
//  5.新增单词
const addNeword = () => {
  setIsModalVisible(true)
}
//  6.更多操作
const moreOperation = (value) =>{
  // 判断是否选择了数据
  if(!selectedRowKeys.length){
    notification.warning({
      message: '请至少选择一项数据',
      duration:1.5
    });
    return
  }
  
  const data = dataSource.filter((i)=>selectedRowKeys.includes(i.id))

  setSelectData(dataSource.filter((i)=>selectedRowKeys.includes(i.id)))

  switch (value.key) {
   case 'addLabel':
    //  新增标签
    if(data.some(i=>i.wordStatus==='P')){
      notification.warning({
        message: '你的选择中含有已发布的数据，请重新选择',
        duration:1.5
      });
      return
    }
    setIsModalVisibleAddLabel(true)
    break
    case 'delLabel':
      //  删除标签
      if(data.some(i=>i.wordStatus==='P')){
        notification.warning({
          message: '你的选择中含有已发布的数据，请重新选择',
          duration:1.5
        });
        return
      }
      setIsModalVisibleDelLabel(true)
    break
    case 'taskOther':
    //  分配任务
    if(data.some(i=>i.wordStatus==='P')){
      notification.warning({
        message: '你的选择中含有已发布的数据，请重新选择',
        duration:1.5
      });
      return
    }
    setIsModalVisibleTask(true)
    break
    case 'statusCheck':
     //  修改状态
     setIsModalVisibleStatus(true)
    break
    case 'pushTestArea':
      //  添加到测试区
      confirm({
        title: '是否将选中的数据添加到测试区',
        icon: <ExclamationCircleOutlined />,
        onOk() {
         const http = async()=>{
          await pushPool({
            dataId: data.map(i => i.id),
            levelId: 255,
            poolId: 601,
            type: 'WORD'
          })

          notification.success({
            message: '添加成功',
            duration:1.5
          });
         }

         http()
        },
        onCancel() {
          // 取消
        },
      });
     break
   default:
     return
  }
}
// 6.1.更多操作
const menu = (
 <Menu
    onClick={moreOperation}
    items={props.userBtnRole.includes('WORD_BUTTON_ONE')?[
      {
        label: '新增标签',
        key: 'addLabel',
      },
      {
        label: '移除标签',
        key: 'delLabel',
      },
      {
        label: '任务分配',
        key: 'taskOther',
      },
      {
        label: '状态退回',
        key: 'statusCheck',
      },
      {
        label: '添加至测试区',
        key: 'pushTestArea',
      },
    ]:[{
      label: '添加至测试区',
      key: 'pushTestArea',
    },
  ]}
  />
);
// 7.获取时间
const getUpdateTime = (value,dataString) => {
  const data = form.getFieldValue()
  data.startTime=dataString[0]
  data.endTime=dataString[1]
  form.setFieldsValue(data)
}


return <div className="app-content animate__animated  animate__fadeIn">
    {/* 表单 */}
    <LlxForm form={form} formItem={expand?formItem:formItem.filter((i,j)=>j<5)}/>
    {/* 操作按钮 */}
    <div className="operate-btn">
     <div>
       {
          !props.examineStatus ?  <Button  onClick={addNeword} type='primary' className='animate__animated animate__fadeInLeft'>新增</Button>:''
       }
       {
         !props.examineStatus ? <Dropdown overlay={menu}>
         <Button  className='animate__animated animate__fadeInLeft'>
           <Space>
            更多操作
           <DownOutlined />
          </Space>
        </Button>
       </Dropdown>:''
       }
       </div>
       <div>
         <Button  onClick={getNewList} type='primary' className='animate__animated animate__fadeInRight'>查询</Button>
          <Button  type='primary' onClick={resetForm} className='animate__animated animate__fadeInRight'>重置</Button>
          <Button  type='link' onClick={()=>setExpand(i=>!i)} className='animate__animated animate__fadeInRight'>{expand?'收起':'展开'}</Button>
       </div>
    </div>

    <Divider />
    {/* 表格 */}
    <LlxTable
     loading={loading} 
     pagination={pagination}
     setPagination={setPagination}
     selectedRowShow={true}
     rowSelection={rowSelection.current}
     height={!expand?320:380}
     total={total}
     getNewList={getNewList}
     columns={columns}
     dataSource={dataSource}/>

     {/* 弹框 */}
     {/* 1.新增 */}
     <AddWord dictionaries={dictionaries} getNewList={getNewList} userName={props.userInfo.user.userName}  isModalVisible={isModalVisible} setIsModalVisible={setIsModalVisible}></AddWord>
      {/* 新增标签 */}
     <AddLabel type='WORD' userName={props.userInfo.user.userName} getNewList={getNewList} labelOption={dictionaries.Label} list={selectData} isModalVisible={isModalVisibleAddLabel} setIsModalVisible={setIsModalVisibleAddLabel} ></AddLabel>
     {/* 移除标签 */}
     <DelLabel type='WORD' userName={props.userInfo.user.userName} getNewList={getNewList} labelOption={dictionaries.Label} list={selectData} isModalVisible={isModalVisibleDelLabel} setIsModalVisible={setIsModalVisibleDelLabel} ></DelLabel>
     {/* 任务分配 */}
     <TaskAllocation  editHttp={wordStatusChangeBatch} type={'WORD'} statusType={'wordStatus'}  userName={props.userInfo.user.userName} getNewList={getNewList} UserSpecies={dictionaries.UserSpecies} list={selectData} isModalVisible={isModalVisibleTask} setIsModalVisible={setIsModalVisibleTask} ></TaskAllocation>
     {/* 状态变更 */}
     <ChangeStatus http={wordStatusChanges} type={'WORD'} statusType={'wordStatus'}  userName={props.userInfo.user.userName} getNewList={getNewList} labelOption={dictionaries.Label} list={selectData} isModalVisible={isModalVisibleStatus} setIsModalVisible={setIsModalVisibleStatus} ></ChangeStatus>
  
     {/* 快速审核弹框 */}
     <ExamineWord getNewList={getNewList} dictionaries={dictionaries} examineData={examineData} isModalVisible={isModalVisibleExamineWord} setIsModalVisible={setIsModalVisibleExamineWord}></ExamineWord>
  </div>
}

// 映射方法
const mapDispatchToProps = (dispatch) => {
  return {
    getUserRoleFn: (data) => dispatch(getUserRole(data)),
    addRouter: (route) => dispatch(addHistoryRouter(route)),
    setPageDataFn: (url,data) => dispatch(setPageData(url,data)),
    setDictionaries: (url,data) => dispatch(setDictionaries(url,data)),
    getCount: (data) => dispatch(getCount(data)),
  }
}

export default connect((state)=>{
  return {tabList:state.tabList,examineStatus:state.examineStatus,userInfo:state.userInfo,dictionaries:state.dictionaries,userBtnRole:state.userBtnRole}
},mapDispatchToProps)(WordLibrary)
